package cn.jhh.content.service.impl;

import cn.jhh.content.model.dto.CourseCategoryTreeDto;
import cn.jhh.content.model.entity.CourseCategory;
import cn.jhh.content.mapper.CourseCategoryMapper;
import cn.jhh.content.service.CourseCategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author jhh
 * @since 2025-05-23
 */
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {
    
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes() {
        // 1. 查询所有课程分类
        LambdaQueryWrapper<CourseCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourseCategory::getIsShow, 1); // 只查询显示的课程分类
        queryWrapper.orderByAsc(CourseCategory::getOrderby); // 按照排序字段排序
        List<CourseCategory> courseCategoryList = this.list(queryWrapper);

        // 2. 将课程分类列表转换为树形结构的DTO列表
        // 先将所有分类按照id分组，方便后续查找父节点
        Map<String, CourseCategoryTreeDto> categoryMap = courseCategoryList.stream()
                .map(category -> {
                    CourseCategoryTreeDto dto = new CourseCategoryTreeDto();
                    BeanUtils.copyProperties(category, dto);
                    return dto;
                })
                .collect(Collectors.toMap(CourseCategory::getId, dto -> dto));

        // 3. 构建树形结构
        List<CourseCategoryTreeDto> result = new ArrayList<>();
        courseCategoryList.forEach(category -> {
            CourseCategoryTreeDto currentNode = categoryMap.get(category.getId());
            if ("0".equals(category.getParentid())) {
                // 如果是根节点，直接加入结果列表
                result.add(currentNode);
            } else {
                // 如果不是根节点，找到父节点并添加到父节点的子节点列表中
                CourseCategoryTreeDto parentNode = categoryMap.get(category.getParentid());
                if (parentNode != null) {
                    if (parentNode.getChildrenTreeNodes() == null) {
                        parentNode.setChildrenTreeNodes(new ArrayList<>());
                    }
                    parentNode.getChildrenTreeNodes().add(currentNode);
                }
            }
        });

        return result;
    }
}
